import { UtilsService } from '@app/utils';
import { Body, Controller, Get, HttpStatus, Param, ParseIntPipe, Post, Query, Req, Res } from '@nestjs/common';
import { RechargeService } from './recharge.service';


@Controller('recharge')
export class RechargeController {

    constructor(
        private service:RechargeService,
        private readonly utils:UtilsService,
        
        
    ) {}


    @Get('options')
    async options() {
        const options = await this.service.options()
        return this.utils.successRes(options)
    }

    @Post('pay')
    async pay(@Body('id', ParseIntPipe) id:number, @Req() { user, userId, isWx, clientSource }) {
        if(id < 1) return
        const res = await this.service.recharge(id, userId, clientSource, isWx, user.openid)
        return res == null ? this.utils.failRes() : this.utils.successRes(res)
    }

    @Post('notify/:client/:id')
    async notify(@Param('id') id:string, @Param('client') client:string, @Body() data:any, @Res() res) {
        try {
            if(client == 'wx') {
                if(data.event_type == 'TRANSACTION.SUCCESS') {
                    const r = await this.service.notify(id, data.resource, true)
                    if(r) {
                       res.status(HttpStatus.OK).send();
                    }else {
                        res.status(HttpStatus.NOT_IMPLEMENTED).send({code : 'FAIL', message : "失败"});
                    }
                }     
                
            }else { //支付宝
                
                if(data.trade_status == 'TRADE_SUCCESS') {
                    const r = await this.service.notify(id, data, false)
                    if(r) {
                        res.status(HttpStatus.OK).send();
                     }else {
                         res.status(HttpStatus.NOT_IMPLEMENTED).send({code : 'FAIL', message : "失败"});
                     }
                }
                
            }

            return
        } catch (error) {
            
        }
        
        res.status(HttpStatus.NOT_IMPLEMENTED).send({code : 'FAIL', message : "失败"});
    }


    @Get('page')
    async page(@Query() query:Pagination, @Req() { userId }) {
        let rows = await this.service.page(query, userId)
        return this.utils.successRes(rows)
    }
}
